package team.umbc;

import org.json.JSONException;

import com.facebook.android.FacebookError;

import android.app.Service;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.IBinder;

public class FriendService extends Service {

	static final int DELAY = 60000;
	private boolean runFlag = false;
	private Updater updater;

	FriendsDB friends;
	SQLiteDatabase db;

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		friends = new FriendsDB(this);
		this.updater = new Updater();
	}

	@Override
	public int onStartCommand(Intent intent, int flag, int startId) {
		if (!runFlag) {
			this.runFlag = true;
			this.updater.start();
		}
		return Service.START_STICKY;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		this.runFlag = false;
		this.updater.interrupt();
		this.updater = null;
	}

	private class Updater extends Thread {

		public Updater() {
			super("PlaceService-Updater");
		}

		@Override
		public void run() {
			FriendService service = FriendService.this;
			if (service.runFlag) {
				PlaceApplication check = (PlaceApplication) service.getApplication();
				try {
					check.fetchFriends();
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (FacebookError e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		}
	}
}
